﻿using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;
using DataStore;
using DataStore.Domain;
using DataStore.Repositories;
using Infrastructure.CurrentData;
using Microsoft.Practices.Composite.Events;

namespace Infrastructure.ViewModels
{
    /// <summary>
    /// AllPeople viewmodel
    /// </summary>
    public class AllPeopleViewModel: DataModel
    {
        
        readonly ObservableCollection<PersonViewModel> _people = new ObservableCollection<PersonViewModel>();


        /// <summary>
        /// Initializes a new instance of the <see cref="AllPeopleViewModel"/> class.
        /// </summary>
        /// <param name="eventAggregator">The event aggregator.</param>
        public AllPeopleViewModel(IEventAggregator eventAggregator)
            : base(eventAggregator)
        {
            RefreshPeople();
        }

        /// <summary>
        /// Refreshes the people.
        /// </summary>
        public void RefreshPeople()
        {
            if (!ThreadPool.QueueUserWorkItem(FetchPeopleCallback))
            {
                State = ModelState.Invalid;
            }
        }

        /// <summary>
        /// Fetches the people callback.
        /// </summary>
        /// <param name="state">The state.</param>
        private void FetchPeopleCallback(object state)
        {
            IDatabase database = Current.Container.Resolve<IDatabase>();
            var unitOfWork = database.CreateUnitOfWork();

            try
            {
                IRepository<Person> repository = new PersonRepository(unitOfWork);
                var people = repository.All;

                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            _people.Clear();
                                            foreach (Person person in people)
                                            {
                                                _people.Add(new PersonViewModel(EventAggregator, person));
                                            }

                                            unitOfWork.Dispose();

                                            State = ModelState.Active;
                                        }),
                    DispatcherPriority.ApplicationIdle);
            }
            catch (Exception e)
            {
                Log.Error("Failed to load People", e);

                unitOfWork.Dispose();
                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            State = ModelState.Invalid;
                                        }),
                    DispatcherPriority.ApplicationIdle);

            }
        }

        /// <summary>
        /// Gets the people.
        /// </summary>
        /// <value>The people.</value>
        public ObservableCollection<PersonViewModel> People
        {
            get
            {
                VerifyCalledOnUIThread();
                return _people;
            }
        }

    }
}